#! /usr/bin/env bash

bssid=$1
essid=$2
delay=$3
pause=$4

if [ -z "$bssid" ]
then
	echo Usage: $(basename $0) bssid [essid] [delay] [pause]
	exit
fi

if [ -z "$delay" ]
then
	delay=0
fi

if [ -z "$pause" ]
then
	pause=5
fi

echo $$ >> "$(echo $0 | sed s/\.sh$//).pid"

cd "$(dirname "$0")"
cd ..

identifier=$(echo $bssid | tr '[A-Z]' '[a-z]' | tr --delete ':')
if [ -n "$essid" ]
then
	identifier=$identifier-$(echo $essid | tr '[A-Z]' '[a-z]' | tr --complement --delete '[a-z0-9]')
fi

cd capture
mkdir -p $identifier
cd $identifier

sleep $delay

fudge=4
brute=1

while [ ! -f key.txt ]
do
	source=
	if [ -f capture.ivs ]
	then
		source=capture.ivs
	fi
	if ls -1 ????-??-??-??-??-??-??.cap &> /dev/null
	then
		source="$source $(ls -1 --reverse ????-??-??-??-??-??-??.cap | head --lines 1)"
	fi

	aircrack-ng -1 -b $bssid -f $fudge -l key.txt -s -x$brute -z $source

	if [ $brute -lt 2 ]
	then
		brute=$(($brute + 1))
	else
		brute=0

		if [ $fudge -lt 8 ]
		then
			fudge=$(($fudge * 2))
		else
			fudge=2
		fi
	fi

	echo
	echo
	echo
	echo $(date +"%Y-%m-%d %H:%M:%S") Cracking fudge $fudge brute $brute
	echo
	sleep $pause
done

